//
//  MYGPatientAddView.swift
//  MYDoctor
//
//  Created by 王振明 on 2024/4/18.
//

import UIKit
import JXSegmentedView
import BRPickerView
import CoreImage
import IQKeyboardManagerSwift
import Moya
class MYGPatientAddView: UIView {
    var writeV:MYGPatientAddWriteView = MYGPatientAddWriteView()
    var name:String = ""
    var gender:Int = 0
    var birthday:String = ""
    var phone:String = ""
    var dismissBlock:(() -> ())?
    var selectIndex:Int = 0{
        didSet{
            initUI()
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    @objc func cancelAction(){
        if let c = dismissBlock {
            c()
        }
    }
    
    @objc private func sureClickAction(){
        if sureBtn.isSelected{
            if let c = dismissBlock {
                c()
            }
            return
        }
        MYGLoading.show()// "doctor_id":MYGUserManager.getUser()?.doctor.id ?? 0,
        MYGNetwork<MYGHomePageAPI, MYGEmptyModel>.request(target: .addPatient(param: [
            "name":writeV.nameTextField.text ?? "",
            "gender":writeV.sexTextField.text == "男" ? 1 : 2,
            "birthday":writeV.birthdayTextField.text ?? "",
            "phone":writeV.phoneTextField.text ?? ""])) {[weak self] item in
                MYGLoading.hide()
                NotificationCenter.default.post(name: NSNotification.Name.init("refreshMyPatientList"), object: nil)
                if let c = self?.dismissBlock {
                    c()
                }
            } failed: { _, error in
                MYGLoading.hide()
                MMYGHUD.showToast(text: error)
            }
    }
    func initUI(){
        self.backgroundColor = .rgba(0, 0, 0,0.6)
        addSubview(backV)
        backV.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.left.equalToSuperview().offset(30)
            make.right.equalToSuperview().offset(-30)
            make.height.equalTo(389)
        }
        backV.addSubview(titleLab)
        titleLab.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(13)
            make.height.equalTo(24)
        }
        backV.addSubview(segmentedView)
        segmentedView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(SCALEWIDTH(45))
            make.top.equalTo(titleLab.snp.bottom).offset(10)
        }
        backV.addSubview(listContainerView)
        listContainerView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-50)
            make.top.equalTo(segmentedView.snp.bottom).offset(0)
        }
        //关联listContainer
        segmentedView.listContainer = listContainerView
        backV.addSubview(cancelBtn)
        cancelBtn.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.bottom.equalToSuperview()
            make.height.equalTo(50)
            make.width.equalTo((screenWidth - 60)/2)
        }
        backV.addSubview(sureBtn)
        sureBtn.snp.makeConstraints { make in
            make.right.equalToSuperview()
            make.bottom.equalToSuperview()
            make.height.equalTo(50)
            make.width.equalTo((screenWidth - 60)/2)
        }
    }
    private lazy var selectVi:MYGCaseFileSelectView = {
       let cont = MYGCaseFileSelectView()
        
        return cont
    }()
    private lazy var backV: UIView = {
        let cont = UIView()
        cont.backgroundColor = .white
        cont.layerCornerRadius = 12
        return cont
    }()
    lazy var titleLab: UILabel = {
        let cont = UILabel()
        cont.text = "新增患者"
        cont.font = .regular(17)
        cont.textColor = .rgba(54, 54, 54, 1)
        return cont
    }()
    private lazy var listContainerView: JXSegmentedListContainerView = {
        let vi = JXSegmentedListContainerView(dataSource: self)
        return vi
    }()
    private lazy var segmentedView: JXSegmentedView = {
        let segmentedView = JXSegmentedView()
        segmentedView.delegate = self
        segmentedView.dataSource = dataSource
        segmentedView.defaultSelectedIndex = selectIndex
        let indicator = JXSegmentedIndicatorLineView()
        indicator.indicatorWidth = SCALEWIDTH(16)
        indicator.indicatorHeight = SCALEWIDTH(3)
        indicator.indicatorColor = .rgba(32, 92, 255, 1)
        segmentedView.indicators = [indicator]
        return segmentedView
    }()
    
    private lazy var dataSource: JXSegmentedTitleDataSource = {
        let dataSource = JXSegmentedTitleDataSource()
        dataSource.titles = ["填写信息","二维码邀请"]
        dataSource.titleNormalFont = .regular(13)
        dataSource.titleNormalColor = .rgba(118, 118, 118, 1)
        dataSource.titleSelectedFont = .regular(16)
        dataSource.titleSelectedColor = .rgba(32, 92, 255, 1)
        dataSource.isItemSpacingAverageEnabled = true
        //        dataSource.itemSpacing = SCALEWIDTH(20)
        //        dataSource.itemWidthIncrement = 12
        return dataSource
    }()
    private lazy var cancelBtn:UIButton = {
        let vi = UIButton()
        vi.setTitle("取消", for: .normal)
        vi.titleLabel?.font = .regular(17)
        vi.setTitleColor(.rgba(102, 102, 102), for: .normal)
        vi.addTarget(self, action: #selector(cancelAction), for: .touchUpInside)
        vi.layer.borderWidth = 0.5
        vi.layer.borderColor = RGBA(r: 212, g: 212, b: 212, a: 1).cgColor
        return vi
    }()
    private lazy var sureBtn:UIButton = {
        let vi = UIButton()
        vi.setTitle("确认", for: .normal)
        vi.titleLabel?.font = .regular(17)
        vi.setTitleColor(.rgba(69, 131, 250, 1), for: .normal)
        vi.addTarget(self, action: #selector(sureClickAction), for: .touchUpInside)
        vi.layer.borderWidth = 0.5
        vi.layer.borderColor = RGBA(r: 212, g: 212, b: 212, a: 1).cgColor
        return vi
    }()
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
extension MYGPatientAddView: JXSegmentedViewDelegate{
    //点击选中或者滚动选中都会调用该方法。适用于只关心选中事件，而不关心具体是点击还是滚动选中的情况。
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
        if index == 1{
            sureBtn.isSelected = true
        }else{
            sureBtn.isSelected = false
        }
    }
    // 点击选中的情况才会调用该方法
    func segmentedView(_ segmentedView: JXSegmentedView, didClickSelectedItemAt index: Int) {}
    // 滚动选中的情况才会调用该方法
    func segmentedView(_ segmentedView: JXSegmentedView, didScrollSelectedItemAt index: Int) {}
    // 正在滚动中的回调
    func segmentedView(_ segmentedView: JXSegmentedView, scrollingFrom leftIndex: Int, to rightIndex: Int, percent: CGFloat) {}
}
extension MYGPatientAddView:JXSegmentedListContainerViewDataSource{
    //返回列表的数量
    func numberOfLists(in listContainerView: JXSegmentedListContainerView) -> Int {
        return 2
    }
    //返回遵从`JXSegmentedListContainerViewListDelegate`协议的实例
    func listContainerView(_ listContainerView: JXSegmentedListContainerView, initListAt index: Int) -> JXSegmentedListContainerViewListDelegate {
        if index == 0{
            return writeV
        }else{
            return MYGPatientAddCodeView()
        }
    }
    
}

class MYGPatientAddWriteView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        initUI()
    }
    @objc func tapAction(){
        IQKeyboardManager.shared.resignFirstResponder()
        BRStringPickerView.showPicker(withTitle: "请选择性别", dataSourceArr: ["男","女"], select: 0) {[weak self] item in
            self?.sexTextField.text = item?.value ?? ""
        }
    }
    @objc func birthdayAction(){
        IQKeyboardManager.shared.resignFirstResponder()
        self.dateBackView.isHidden = false
        UIViewController.keyWindow?.bringSubviewToFront(self.dateBackView)
    }
    func initUI(){
        addSubviews([nameTextField,sexTextField,birthdayTextField,phoneTextField])
        nameTextField.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(18.5)
            make.right.equalToSuperview().offset(-18.5)
            make.top.equalToSuperview().offset(20)
            make.height.equalTo(40)
        }
        sexTextField.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(18.5)
            make.right.equalToSuperview().offset(-18.5)
            make.top.equalTo(nameTextField.snp.bottom).offset(15)
            make.height.equalTo(40)
        }
        birthdayTextField.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(18.5)
            make.right.equalToSuperview().offset(-18.5)
            make.top.equalTo(sexTextField.snp.bottom).offset(15)
            make.height.equalTo(40)
        }
        phoneTextField.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(18.5)
            make.right.equalToSuperview().offset(-18.5)
            make.top.equalTo(birthdayTextField.snp.bottom).offset(15)
            make.height.equalTo(40)
        }
        UIViewController.keyWindow?.addSubview(dateBackView)
        dateBackView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    private lazy var dateBackView:UIView = {
        let cont = UIView()
        cont.backgroundColor = .rgba(51, 51, 51,0.3)
        cont.isHidden = true
        cont.addSubview(datePicker)
        datePicker.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(SCALEWIDTH(200))
        }
        let vi = UIView()
        vi.backgroundColor = .white
        cont.addSubview(vi)
        vi.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(datePicker.snp.top)
            make.height.equalTo(SCALEWIDTH(40))
        }
        let btn = UIButton()
        btn.setTitle("确定", for: .normal)
        btn.titleLabel?.font = .regular(15)
        btn.setTitleColor(.blue, for: .normal)
        btn.addTarget(self, action: #selector(doneDateSelect), for: .touchUpInside)
        vi.addSubview(btn)
        btn.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-SCALEWIDTH(20))
            make.bottom.top.equalToSuperview()
            make.width.equalTo(SCALEWIDTH(40))
        }
        return cont
    }()
    //确定日期选择
    @objc func doneDateSelect() {
        dateBackView.isHidden = true
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        let currentDateString = formatter.string(from: datePicker.date)
        birthdayTextField.text = currentDateString
        dateBackView.isHidden = true
    }
    //MARK: lazy
    private lazy var datePicker:UIDatePicker = {
        let cont = UIDatePicker()
        cont.datePickerMode = .date
        if #available(iOS 13.4, *) {
            cont.preferredDatePickerStyle = .wheels
        } else {
            // Fallback on earlier versions
        }
        cont.locale = Locale(identifier: "zh_CN")
        cont.backgroundColor = .white
        return cont
    }()
    lazy var nameTextField: UITextField = {
        let tf = UITextField()
        tf.font = .regular(15)
        tf.textColor = .rgba(51, 51, 51)
        tf.backgroundColor = .rgba(243, 243, 243, 1)
        tf.layer.masksToBounds = true
        tf.layer.cornerRadius = 2.5
        tf.leftViewMode = .always
        tf.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 14, height: 1))
        tf.attributedPlaceholder = NSMutableAttributedString.rz.colorfulConfer(confer: { confer in
            confer.text("患者姓名")?.font(.regular(14)).textColor(.rgba(142, 142, 147, 1))
        })
        //         tf.addTarget(self, action: #selector(screenAction), for: .editingChanged)
        //tf.delegate = self
        return tf
    }()
    lazy var sexTextField: UITextField = {
        let tf = UITextField()
        tf.font = .regular(15)
        tf.textColor = .rgba(51, 51, 51)
        tf.backgroundColor = .rgba(243, 243, 243, 1)
        tf.layer.masksToBounds = true
        tf.layer.cornerRadius = 2.5
        tf.layer.borderWidth = 0.5
        tf.leftViewMode = .always
        tf.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 14, height: 1))
        tf.layer.borderColor = RGBA(r: 212, g: 212, b: 212, a: 1).cgColor
        tf.attributedPlaceholder = NSMutableAttributedString.rz.colorfulConfer(confer: { confer in
            confer.text("患者性别")?.font(.regular(14)).textColor(.rgba(142, 142, 147, 1))
        })
        let tap = UITapGestureRecognizer(target: self, action: #selector(tapAction))
        tf.addGestureRecognizer(tap)
        //         tf.addTarget(self, action: #selector(screenAction), for: .editingChanged)
        //tf.delegate = self
        return tf
    }()
    lazy var birthdayTextField: UITextField = {
        let tf = UITextField()
        tf.font = .regular(15)
        tf.textColor = .rgba(51, 51, 51)
        tf.backgroundColor = .rgba(243, 243, 243, 1)
        tf.layer.masksToBounds = true
        tf.layer.cornerRadius = 2.5
        tf.layer.borderWidth = 0.5
        tf.leftViewMode = .always
        tf.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 14, height: 1))
        tf.layer.borderColor = RGBA(r: 212, g: 212, b: 212, a: 1).cgColor
        tf.attributedPlaceholder = NSMutableAttributedString.rz.colorfulConfer(confer: { confer in
            confer.text("出生日期")?.font(.regular(14)).textColor(.rgba(142, 142, 147, 1))
        })
        let tap = UITapGestureRecognizer(target: self, action: #selector(birthdayAction))
        tf.addGestureRecognizer(tap)
        //         tf.addTarget(self, action: #selector(screenAction), for: .editingChanged)
        //tf.delegate = self
        return tf
    }()
    lazy var phoneTextField: UITextField = {
        let tf = UITextField()
        tf.font = .regular(15)
        tf.textColor = .rgba(51, 51, 51)
        tf.backgroundColor = .rgba(243, 243, 243, 1)
        tf.layer.masksToBounds = true
        tf.layer.cornerRadius = 2.5
        tf.layer.borderWidth = 0.5
        tf.leftViewMode = .always
        tf.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 14, height: 1))
        tf.layer.borderColor = RGBA(r: 212, g: 212, b: 212, a: 1).cgColor
        tf.attributedPlaceholder = NSMutableAttributedString.rz.colorfulConfer(confer: { confer in
            confer.text("手机号，用于邀请患者完善病历")?.font(.regular(14)).textColor(.rgba(142, 142, 147, 1))
        })
        //         tf.addTarget(self, action: #selector(screenAction), for: .editingChanged)
        //tf.delegate = self
        return tf
    }()
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
class MYGPatientAddCodeView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        initUI()
    }
    func initUI(){
        addSubview(backV)
        backV.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(20)
            make.centerX.equalToSuperview()
            make.size.equalTo(CGSize(width: 150, height: 150))
        }
        guard let uid = MYGUserManager.getUser()?.id else {return}
        
        
        let token = MYGUserManager.user?.verification_token ?? ""
        let doctor_id = MYGUserManager.user?.doctor.id ?? 0
        
        let  urlString = "\(BaseUrl)/api/doctor/add_patient_qr?token=\(token)&doctor_id=\(doctor_id)"
        let url = URL(string: urlString)
    
        self.backV.sd_setImage(with:url)
        
        
//        let provider = MoyaProvider<MYGSurgicalApi>()
//        provider.request(MYGSurgicalApi.getInviteQRStr(params: ["doctor_id":uid])) { result in
//            switch result {
//            case let .success(data):
//                let qrData: Data = data.data
//                self.backV.image = UIImage(data: qrData)
//            case .failure(_): break
//                
//            }
//        }
    }
    private lazy var backV: UIImageView = {
        let cont = UIImageView()
//        cont.image = generateQRCode(for: "1")
        return cont
    }()
    func generateQRCode(for string: String) -> UIImage? {
        let context = CIContext()
        // 创建一个 CIFilter 对象，并设置其属性：
        if let filter = CIFilter(name: "CIQRCodeGenerator") {
            // 设置输入数据
            let data = string.data(using: .isoLatin1)
            filter.setValue(data, forKey: "inputMessage")
            
            // 设置纠错级别，可选值：L(7%), M(15%), Q(25%), H(30%)
            filter.setValue("H", forKey: "inputCorrectionLevel")
            
            // 获取生成的二维码图像
            if let outputImage = filter.outputImage {
                // 将图像转换为可显示的 CGImage
                if let cgImage = context.createCGImage(outputImage, from: outputImage.extent) {
                    // 创建 UIImage 并显示
                    let qrCodeImage = UIImage(cgImage: cgImage)
                    return qrCodeImage
                    // 在这里使用 qrCodeImage，可以将其显示到 UIImageView 或者保存到文件中
                }
            }
        }
        return UIImage()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
extension MYGPatientAddCodeView:JXSegmentedListContainerViewListDelegate {
    
    func listView() -> UIView {
        return self
    }
}
extension MYGPatientAddWriteView:JXSegmentedListContainerViewListDelegate {
    
    func listView() -> UIView {
        return self
    }
}
